# 导入包
import websocket
import json

# 创建事件回调函数
def on_open(ws_app):
    print('已连接')
    # part1 = [0x08, 0xC8, 0x01, 0x1A, 0x87, 0x01, 0x0A, 0x58]  # 不变的头
    # # token是从https://live.kuaishou.com/live_api/liveroom/websocketinfo?liveStreamId=Lr4b0VjQxKc这个数据包里响应回来的
    # # 然而这个数据包携带 liveStreamId=Lr4b0VjQxKc 我猜他是从点击进来的页面中携带的
    # token = "9hPt+I039DjrzZuIo4gdOGTc8vtSeXwWDU5YU28P0E6wTHSQ1YVr5C+QlnaSPRWs5uKo4St3/H30RyKpKTc6HwIUBqlIwaMTgqez7oYg3PX05DLk8RVtwnqqKCU4KKHXSXwD5TYanY0nVCauODEyN3UVIz7uGgJyq4iBEvG1HHY="
    # part2 = [ord(c) for c in token]
    # part3 = [0x12, 0x0B]  #
    # stream_id = "Lr4b0VjQxKc"
    # part4 = [ord(c) for c in stream_id]
    # part5 = [0x3A, 0x1E]
    # # pageId是从session里面来的
    # page_id = "zdXdwzb9K3T9n0Q2_1709814265264"
    # part6 = [ord(c) for c in page_id]
    #
    # d = part1 + part2 + part3 + part4 + part5 + part6
    # print(d)

    arguments = {
        "type": "CS_ENTER_ROOM",
        "payload": {
            "liveStreamId": "Lr4b0VjQxKc",
            "token": "9hPt+I039DjrzZuIo4gdOGTc8vtSeXwWDU5YU28P0E6wTHSQ1YVr5C+QlnaSPRWs5uKo4St3/H30RyKpKTc6HwIUBqlIwaMTgqez7oYg3PX05DLk8RVtwnqqKCU4KKHXSXwD5TYanY0nVCauODEyN3UVIz7uGgJyq4iBEvG1HHY=",
            "pageId": "trxsRFkeqQli05Ub_1709817537556"
        }
    }
    json_arguments = json.dumps(arguments)
    ws.send(json_arguments)



def on_message(ws_app, message):
    print(message)


def on_error(ws_app, error):
    print(error)


def on_close(ws_app, a, b):
    print(a, b)
    print('已断开')


# 实例化一个ws客户端
url = "wss://live-ws-group1.kuaishou.com/websocket"
header = {
    "Pragma": "no-cache",
    "Origin": "https://live.kuaishou.com",
    "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,ja;q=0.6,ko;q=0.5",
    "Sec-WebSocket-Key": "d+NBtxbsvVjpi8RxWO425Q==",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
    "Upgrade": "websocket",
    "Cache-Control": "no-cache",
    "Connection": "Upgrade",
    "Sec-WebSocket-Version": "13",
    "Sec-WebSocket-Extensions": "permessage-deflate; client_max_window_bits"
}
ws = websocket.WebSocketApp(
    url=url,
    header=header,
    on_message=on_message,
    on_error=on_error,
    on_open=on_open,
    on_close=on_close,
)

# 开启长连接，进行监听
ws.run_forever()


# 关闭连接
ws.close()
